package net.xiaosaguo.mymall.cart.interceptor;

import net.xiaosaguo.common.constant.AuthConstant;
import net.xiaosaguo.common.constant.CartConstant;
import net.xiaosaguo.common.pojo.vo.MemberVO;
import net.xiaosaguo.mymall.cart.pojo.dto.UserInfoDTO;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * description: 购物车拦截器，处理用户身份标识
 *
 * @author xiaosaguo
 * @date 2020/07/08
 */
// @Component
public class CartInterceptor implements HandlerInterceptor {

    public static final ThreadLocal<UserInfoDTO> USER_INFO = new ThreadLocal<>();

    /**
     * description: 再执行目标方法之前，判断用户登录状态，并封装用户身份标识，如果第一次访问，创建临时身份标识
     *
     * @author xiaosaguo
     * @date 2020/07/08 11:45
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        System.out.println(Thread.currentThread().getId() + "-开始处理用户身份标识...USER_INFO：" + USER_INFO.get());
        UserInfoDTO userInfoDTO = new UserInfoDTO();

        // 获取登录用户的身份标识
        HttpSession session = request.getSession();
        MemberVO member = (MemberVO) session.getAttribute(AuthConstant.LOGIN_USER);
        if (member != null) {
            userInfoDTO.setUserId(member.getId());
        }

        // 获取临时身份标识
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                if (CartConstant.TEMP_USER_COOKIE_NAME.equals(cookie.getName())) {
                    userInfoDTO.setUserKey(cookie.getValue());
                }
            }
        }

        // 如果是第一次访问，没有临时身份标识，生成一个临时身份标识
        if (StringUtils.isEmpty(userInfoDTO.getUserKey())) {
            System.out.println(Thread.currentThread().getId() + "-初次使用生成的临时身份标识...USER_INFO：" + USER_INFO.get());
            String uuid = UUID.randomUUID().toString().replace("-", "");
            userInfoDTO.setUserKey(uuid);
            userInfoDTO.setHasUserKey(false);
        }

        // 在本次请求中共享身份标识
        USER_INFO.set(userInfoDTO);
        System.out.println(Thread.currentThread().getId() + "-身份标识处理完毕...USER_INFO：" + USER_INFO.get());
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // 请求完成后，要保存第一次生成的临时标识到浏览器 cookie 中
        // UserInfoDTO userInfo = USER_INFO.get();
        if (!USER_INFO.get().isHasUserKey()) {
            System.out.println(Thread.currentThread().getId() + "-保存初次生成的临时身份标识...USER_INFO：" + USER_INFO.get());
            Cookie cookie = new Cookie(CartConstant.TEMP_USER_COOKIE_NAME, USER_INFO.get().getUserKey());
            cookie.setDomain("mymall.com");
            cookie.setMaxAge(CartConstant.TEMP_USER_COOKIE_TIMEOUT);
            response.addCookie(cookie);
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 请求 ThreadLocal 中的数据
        System.out.println(Thread.currentThread().getId() + "-清除身份标识...USER_INFO：" + USER_INFO.get());
        USER_INFO.remove();
        System.out.println(Thread.currentThread().getId() + "-清除后的身份标识...USER_INFO：" + USER_INFO.get());
        System.out.println("\n\n");
    }
}
